<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="选择商品">
          <el-button type="primary" @click="chooseGood">选择商品</el-button>
        </el-form-item>
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="form.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="初始销量" prop="sales_initial">
          <el-input v-model="form.sales_initial"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="kc">
          <el-input v-model="form.kc"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec"></el-input>
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort"></el-input>
        </el-form-item>-->
        <el-form-item label="分类" prop="class_id">
          <!-- <el-select
            v-model="form.class_id"
            @focus="getCategoryList"
            placeholder="请选择分类"
            :loading="optionLoading"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.class_name"
              :value="item.id"
            ></el-option>
          </el-select>-->
          <el-cascader
            v-model="form.class_id"
            :options="dialogoptions"
            :props="{ checkStrictly: true,value:'id',label:'class_name' }"
            placeholder="请选择分类"
            clearable
            :disabled="true"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="是否限购" prop="is_limit">
          <el-radio-group v-model="form.is_limit">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否首页展示" prop="is_index">
          <el-select v-model="form.is_index" placeholder="请选择是否首页展示">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否虚拟" prop="is_virtual">
          <el-radio-group v-model="form.is_virtual">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架" prop="is_show">
          <el-select v-model="form.is_show" placeholder="请选择是否上架">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否预售" prop="is_ys">
          <el-select style="width:360px" v-model="form.is_ys" placeholder="请选择是否预售">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预售时间" prop="is_ys">
          <el-date-picker
            style="width:360px"
            :disabled="form.is_ys==0"
            v-model="form.ys_time"
            type="datetime"
            placeholder="选择预售时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="是否积分购买" prop="is_integral">
          <el-select v-model="form.is_integral" placeholder="请选择是否积分购买" @change="changePay">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" :disabled="form.is_integral==1"></el-input>
        </el-form-item>
        <el-form-item label="积分价格" prop="integral">
          <el-input v-model="form.integral" :disabled="form.is_integral==0"></el-input>
        </el-form-item>
        <el-form-item label="是否包邮" prop="is_by">
          <el-select v-model="form.is_by" placeholder="请选择是否包邮" :disabled="form.is_integral==1">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片" prop="img">
          <el-upload
            class="avatar-uploader"
            action="https://upload-z0.qiniup.com/"
            :data="postData"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品组图">
          <el-upload
            action="https://upload-z0.qiniup.com/"
            :data="postData"
            list-type="picture-card"
            ref="pictureUpload"
            :file-list="fileList"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品详情">
          <tinymce v-model="form.details" :height="300" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      title="商品库"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <div class="query-card">
        <!-- <el-row type="flex" align="middle">
        <el-col :span="12">-->
        <div class="grid-content bg-purple search">
          <el-form ref="query" :model="query" label-width="100px">
            <el-form-item style="margin-bottom:0px" label="商品名称">
              <el-input v-model="query.keywords" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px" label="分类">
              <el-cascader
                v-model="query.class_id"
                :options="dialogoptions"
                :props="{ checkStrictly: true,value:'id',label:'class_name' }"
                placeholder="请选择分类"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-form>
        </div>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="queryAsk">查询</el-button>
          <el-button @click="queryReset">重置</el-button>
        </div>
        <!-- </el-col>
        </el-row>-->
      </div>
      <el-table
        :data="goodsData"
        ref="sendmultipleTable"
        border
        tooltip-effect="dark"
        style="width: 100%;margin: 20px 0;"
        @row-click="handleSelectionChange"
        :header-cell-style="{background:'#eee'}"
      >
        <el-table-column align="center" width="55">
          <template slot-scope="scope">
            <el-radio v-model="sendForm.goods_id" :label="scope.row.id">{{""}}</el-radio>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>

        <el-table-column align="center" prop="goods_name" label="商品名称"></el-table-column>
        <el-table-column align="center" label="商品图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="class_name" label="分类"></el-table-column>
        <el-table-column align="center" prop="spec" label="规格"></el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
      <div style="text-align:right;margin-top:20px">
        <el-button type="primary" @click="goodsInfo">确定</el-button>
        <el-button @click="drawer=false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { categoryList } from '@/api/product'
import {
  commodityCategoryList,
  addMangeList,
  editeMangeList
} from '@/api/commodity'
import { upload, productList } from '@/api/system'
import { parseTime } from '../../utils'
export default {
  name: 'CommodityManageEdite',
  components: { Tinymce },
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      // 抽屉
      drawer: false,
      direction: 'rtl',
      //query
      query: {
        keywords: '',
        class_id: ''
      },
      goodsData: [],
      sendForm: {
        goods_id: ''
      },
      goods: '',
      form: {
        is_virtual: '0',
        goods_name: '',
        sort: '',
        class_id: '',
        classId: '',
        is_index: '',
        is_show: '1',
        is_by: '',
        is_ys: '',
        ys_time: '',
        sales_initial: '0',
        is_integral: '0',
        is_limit: '0',
        price: '0',
        integral: '0',
        img: '',
        imgs: [],
        details: '',
        spec: '',
        kc: ''
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        class_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        is_index: [
          { required: true, message: '请选择是否首页展示', trigger: 'blur' }
        ],
        is_virtual: [
          { required: true, message: '请选择是否虚拟', trigger: 'blur' }
        ],
        is_show: [
          { required: true, message: '请选择是否上架', trigger: 'blur' }
        ],
        is_by: [{ required: true, message: '请选择是否包邮', trigger: 'blur' }],
        is_ys: [{ required: true, message: '请选择是否预售', trigger: 'blur' }],
        ys_time: [
          { required: true, message: '请选择预售时间', trigger: 'blur' }
        ],
        sales_initial: [
          { required: true, message: '请输入初始销量', trigger: 'blur' }
        ],
        is_integral: [
          { required: true, message: '请选择是否积分购买', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        integral: [{ required: true, message: '请输入积分', trigger: 'blur' }],
        spec: [{ required: true, message: '请填写规格', trigger: 'blur' }],
        img: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
        kc: [{ required: true, message: '请输入库存', trigger: 'blur' }]
        // imgs: [{ required: true, message: "请上传组图", trigger: "blur" }],
        // details: [
        //   { required: true, message: "请输入商品详情", trigger: "blur" }
        // ]
      },
      options: [],
      // 上传图片
      url: '',
      imageUrl: '',
      postData: {
        token: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      type: '',
      rows: '',
      fileList: [],
      optionLoading: false,
      dialogoptions: []
    }
  },
  mounted() {
    this.getCategoryList()
    this.getCategary()
    let uploadFiles = this.$refs.pictureUpload.uploadFiles
    this.type = this.$route.query.type
    if (this.type == '编辑') {
      this.rows = this.$route.query.rows
      this.rows.ys_time = parseTime(this.rows.ys_time)
      this.rows.classId = JSON.parse(this.rows.classId)
      this.form = this.rows
      console.log(this.form)
      this.imageUrl = this.form.img
      // this.sendForm.goods_id=this.form.class_id
      this.form.imgs.forEach((item, index) => {
        this.fileList.push({ name: index, url: item })
      })
    } else if (this.type == '添加') {
      this.rows = this.$route.query.row
      // this.form.goods_name = this.rows.goods_name;
      // this.form.spec = this.rows.spec;
      // this.form.img = this.rows.img;
      // this.imageUrl = this.form.img;
      this.form.class_id = this.rows.class_id
    }
    this.getToken()
  },
  methods: {
    //获取分类列表
    async getCategoryList() {
      this.optionLoading = true
      const res = await commodityCategoryList({
        page: '1',
        limit: '999',
        keywords: ''
      })
      this.optionLoading = false
      this.options = res.data
      console.log(res)
    },
    // 商品库
    async getProductList() {
      const res = await productList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.keywords,
        class_id: this.query.class_id,
        is_goods: '1'
      })
      console.log(res)
      this.goodsData = res.data
      this.total = res.count
    },
    // 获取商品分类
    async getCategary() {
      const res = await categoryList({
        page: 1,
        limit: 999,
        keywords: '',
        is_goods: '1'
      })
      console.log(res)
      this.dialogoptions = res.data
    },
    chooseGood() {
      this.drawer = true
      this.getProductList()
    },
    handleClose(done) {
      done()
    },
    // 搜索列表
    queryAsk() {
      console.log(this.query)
      this.query.class_id = this.query.class_id[this.query.class_id.length - 1]
      this.currentPage = 1
      this.getProductList()
    },
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.query.class_id = ''
      this.getProductList()
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current
      this.getProductList()
    },
    handleSelectionChange(val) {
      this.goods = val
      this.sendForm.goods_id = val.id
    },
    goodsInfo() {
      this.form.goods_name = this.goods.goods_name
      this.form.spec = this.goods.spec
      this.form.img = this.goods.img
      this.form.classId = JSON.stringify(this.goods.class_id)
      this.form.class_id = this.goods.class_id[0]
      this.imageUrl = this.goods.img
      this.drawer = false
    },
    changePay() {
      if (this.form.is_integral == 1) {
        this.form.is_by = '1'
      }
    },
    onSubmit() {
      if (this.form.is_integral == 1 && this.form.integral == 0) {
        this.$message.error('积分不能为0')
        return
      } else if (this.form.is_integral == 0 && this.form.price == 0) {
        this.$message.error('价格不能为0')
        return
      }
      //组图
      this.form.imgs = []
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      console.log(uploadFiles)
      uploadFiles.forEach((item) => {
        if (item.response) {
          this.form.imgs.push(this.url + item.response.key)
        } else {
          this.form.imgs.push(item.url)
        }
      })
      //如果没有组图默认传封面图
      if (this.form.imgs == []) {
        this.form.imgs = this.form.img
      }
      if (this.form.details == '') {
        this.form.details = `<img src=${this.form.img}></img>`
      }
      //默认传大分类
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.type == '添加') {
            const res = await addMangeList({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            } else {
              console.log(res)
              this.$message.error('添加失败')
            }
          } else if (this.type == '编辑') {
            this.form.classId = JSON.stringify(this.form.classId)
            const res = await editeMangeList({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            } else {
              console.log(res)
              this.$message.error('编辑失败')
            }
          }
        }
      })
    },
    cancel() {
      // 调用全局挂载的方法,关闭当前标签页
      this.$store.dispatch('tagsView/delView', this.$route)
      //返回上一个tab页面 返回上一步路由，
      this.$router.go(-1)
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = this.url + res.key
      this.form.img = this.imageUrl
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return
      }
    },
    async getToken() {
      const res = await upload()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },
    // 商品图组
    handleRemove(file) {
      console.log(file)
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['url'] == file.url) {
          uploadFiles.splice(i, 1)
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  ::v-deep .el-form {
    display: flex;
  }
}
::v-deep .el-input--medium .el-input__inner {
  width: 360px;
}
::v-deep .el-textarea__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  width: 50% !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>